package priv.cwr.springboot.demo.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import priv.cwr.springboot.demo.configuration.UserCenterGlobal;
import priv.cwr.springboot.demo.mapper.UserMapper;
import priv.cwr.springboot.demo.model.vo.UserForm;
import priv.cwr.springboot.demo.utils.RedisLockUtil;

import java.util.List;
import java.util.UUID;

/**
 * User: R
 * Date: 2018/8/30
 * Time: 15:09
 * Created with IntelliJ IDEA.
 */
@Service
public class RedisService {
    private final StringRedisTemplate stringRedisTemplate;
    private static final ObjectMapper OBJECTMAPPER = new ObjectMapper();
    private final UserMapper userMapper;

    public RedisService(StringRedisTemplate stringRedisTemplate,
                        UserMapper userMapper) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.userMapper = userMapper;
    }

    /**
     * 刷新用户列表缓存
     *
     * @param key    key
     * @param deptId 部门id
     */
    @Async("userCenter")
    public void writeUserList(String key, Long deptId) {
        String uuid = UUID.randomUUID().toString();
        try {
            //获取redis分布式锁
            boolean lock = RedisLockUtil.tryGetDistributedLock(stringRedisTemplate, "LOCK_" + key, uuid, 10 * 1000);
            if (lock) {
                List<UserForm> list = this.userMapper.findAllByApp(deptId);
                //如果不为空
                if (list != null && !list.isEmpty()) {
                    //刷新缓存
                    this.stringRedisTemplate.opsForValue().set(
                            key,
                            OBJECTMAPPER.writeValueAsString(list),
                            UserCenterGlobal.USER_LIST_CACHE_TIME,
                            UserCenterGlobal.USER_LIST_CACHE_MINUTES
                    );
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            RedisLockUtil.releaseDistributedLock(stringRedisTemplate, "LOCK_" + key, uuid);
        }
    }
}
